// pages/detail/free.js
import authorize from '../../utils/authorize.js';
import Router from '../../utils/router';
import util from '../../utils/util.js';
import free from '../../services/free.js';
import Record from '../../utils/page-record.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    ceorid: 6, //助力订单id
    first: false, //是否第一次助力
    data: {}, //返回的数据
    end: '', //活动剩余时间
    s: '',
    h: '',
    m: '',
    w: '',
    need_people:10,
    list: '', //正在拿列表
    getArr: [], //多少分钟前
    share_url: '', //分享的图片
    auth: '', //是否授权
    order_status: '', //领取的状态
    money:'',//商品价格
    store_id:'',//店铺id
    disparity:'',//还差多少人
    once:true,//只执行一次
    isShowTips: false, //是否在自己店铺提示
    share:false,//弹出分享组件
    transmit: {
      style: 'position:absolute;width:100%;height:100%;right:0rpx;top:0rpx;opacity:0;',
      value: ''
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let _this = this;
    if (options.ceorid) {
      this.setData({
        ceorid: options.ceorid
      })
    }
    var auth = wx.getStorageSync("user_info").info_authorize;
    this.setData({
      store_id: options.store_id
    })
    if (auth == 1) {
      this.setData({
        auth: 1
      })
    } else {
      this.setData({
        auth: 2
      })
    }
    //在非自己店铺浏览时的提示
    let user_infoStoreId = wx.getStorageSync('user_info').store_id;
    if (_this.data.store_id != user_infoStoreId && user_infoStoreId != null) {
      _this.setData({
        isShowTips: true
      })
    }
    this.firstCheck();
    this.createHtml();
    this.createList();
  },
  //点击返回自己店铺时方法
  goStore() {
    let user_info = wx.getStorageSync('user_info');
    let store_id = user_info.store_id;
    Router.reLaunch('store', `store_id=${store_id}`, 'reLaunch');
  },
  //页面
  createHtml() {
    let _this = this;
    let params = {
      ceorid: _this.data.ceorid
    }
    free.getdetail(params, res => {
      console.log(res)
      if (res.code == 1) {
        _this.setData({
          data: res.data,
          end: res.data.orders.end_time,
          share_url: 'https:' + res.data.orders.share_url,
          order_status: res.data.orders.order_status,
          money: Number(res.data.orders.total_money).toFixed(2),
          need_people: Number(res.data.orders.need_people) > 15 ? 15 : Number(res.data.orders.need_people),
          disparity: util.floatAccSub(res.data.orders.need_people, res.data.orders.have_people),
        })
        console.log(_this.data.share_url)
        var need = util.floatAccDiv(res.data.orders.have_people, res.data.orders.need_people)
        var w = util.floatAccMul(need, 660);
        _this.setData({
          w: w + 'rpx'
        })
        var time = util.floatAccDiv(new Date().getTime(), 1000).toFixed(0);
        var end = util.floatAccSub(_this.data.end, time);
        if(_this.data.once){
          _this.downTime(end)
        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  downTime(time) { //调取定时器
    let _this = this;
    var thistime = setTimeout(function() {
      time--;
      if (time <= -1) {
        clearTimeout(thistime)
        _this.setData({
          s: '00',
          h: '00',
          m: '00',
          once:false
        })
        _this.createHtml();
      } else {
        _this.downTime(time)
        _this.setData({
          s: _this.formatSeconds(time).s,
          h: _this.formatSeconds(time).h,
          m: _this.formatSeconds(time).m,
        })
      }
    }, 1000)
  },
  //检测次数
  firstCheck() {
    let params = {};
    let _this = this;
    free.firstCheck(params, res => {
      console.log(res)
      if (res.code == 200) {
        _this.setData({
          first: true
        })
      }
    })
  },
  //免费拿列表
  createList() {
    let params = {};
    let _this = this;
    free.collage(params, res => {
      if (res.code == 200) {
        _this.setData({
          list: res.data
        })
        var dataList = res.data.dataList;
        var getArr = [];
        if (dataList.length) {
          var now = new Date().getTime();
          for (var i = 0; i < dataList.length; i++) {
            var time = '';
            var timeli = dataList[i].create_time.replace(/-/g, "/");
            if (Math.floor((new Date().getTime() - new Date(timeli).getTime()) / 3600000) < 1) {
              time = Math.floor((new Date().getTime() - new Date(timeli).getTime()) / 60000) + '分钟前' 
            } else {
              time = Math.floor((new Date().getTime() - new Date(timeli).getTime()) / 3600000) + '小时前'
            }
            getArr.push(time)
          }
        }
        _this.setData({
          getArr: getArr
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  //查看大图
  bindImg(event) {
    console.log(event)
    var src = event.currentTarget.dataset.src;
    var url = event.currentTarget.dataset.img;
    var fang = [];
    for (var i = 0; i < url.length; i++) {
      fang.push('https:' + url[i].url)
    }
    wx.previewImage({
      current: src,
      urls: fang
    })
  },
  //授权后再助力
  onGotUserInfo(e) {
    let _this = this;
    if (e.detail.errMsg == 'getUserInfo:ok') {
      _this.setData({
        auth: 1,
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.createHtml();
    this.createList();
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  formatSeconds(value) {
    var _this = this;
    var secondTime = parseInt(value); // 秒
    var minuteTime = 0; // 分
    var hourTime = 0; // 小时
    if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime > 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt(minuteTime / 60);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt(minuteTime % 60);
      }
    }
    var time = {
      s: _this.getZero(secondTime),
      m: _this.getZero(minuteTime),
      h: _this.getZero(hourTime)
    }
    return time;
  },
  getZero(num) { //添加0
    var date = '';
    if (num < 10) {
      date = '0' + num
    } else {
      date = num
    }
    return date
  },
  //去到商品列表页
  goFreecharege() {
    Router.go('freecharege', ``, 'navigateTo')
  },
  //去到提交地址页面
  goAddress() {
    var _this=this;
    Router.go('subaddress', `ceorid=${_this.data.ceorid}`, 'navigateTo')
  },
  //记录分享源
  getEvent(e){
    this.setData({
      share:true
    })
    let num=e.currentTarget.dataset.num;
    let p = getCurrentPages().pop();
    if(num==1){
      Record.clickButton(p, 'Invitation_free')
    }else if(num==2){
      Record.clickButton(p, 'Invitation_free_head')
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    let _this = this;
    let user_id = wx.getStorageSync('user_info').id
    _this.setData({
      first:false
    })
    if (_this.data.auth != 1) {
      return false
    }
    if (res.form === 'button') {
      console.log(res.target)
    }
    var title = wx.getStorageSync('user_info').user_nickname + '@你，快来帮点一下，你也可以免费拿！'
    let paths = 'pages/store/index?store_id=' + _this.data.store_id + '&to=' + encodeURIComponent('/pages/collage/helpfree?ceorid=' + _this.data.ceorid + '&sharerecord=freedetailcard&store_id=' + _this.data.store_id + '&user_id=' + user_id);
    return {
      title: title,
      path: paths,
      imageUrl: _this.data.share_url
    }

  }
})